/*
 * BrianClarkeCPE301Design6STEPPER.c
 *
 * Created: 5/4/2014 8:15:25 PM
 *  Author: Iguana
 */ 
#define F_CPU 8000000UL
#include <avr/io.h>
#include <util/delay.h>

int convert();
void init();

void init()
{
	DDRC = 0x00;									// Set port C to input
	DDRB = 0xFF;									// Open Port B
	ADCSRA = 0x87;									// ADC Enable with Clock/128
	ADMUX = 0x60;									// AVCC VRef with ADC0 for input
}

int convert()
{
	ADCSRA |= (1<<ADSC);							// Start conversion
	while((ADCSRA&(1<<ADIF)) == 0);					// Sit for full conversion
	return (ADCH);									// Return 8 significant bits
}

void motor(int speed)
{
	PORTB = 0X66;									// Turn the motor with a delay of the speed requested
	
	for (int i = 0; i < speed; i++)
		{
		_delay_ms(1);
		}
	PORTB = 0xCC;
	for (int i = 0; i < speed; i++)
	{
		_delay_ms(1);
	}
	PORTB = 0x99;
	for (int i = 0; i < speed; i++)
	{
		_delay_ms(1);
	}
	PORTB = 0x33;
	for (int i = 0; i < speed; i++)
	{
		_delay_ms(1);
	}
}

int main()
{
	init();												// this calls the function to initialize adc conversion using pc0 as input
	while(1)
	{
		int speed = 0;									// Initialize and clear speed
		
		while(1)
		{
			speed = convert(); 							// Grab value from potentiometer
			speed /= 10;								// Convert range from 0-1024,  0->102
			speed += 10;								// Offset the range to 10->112
			motor(speed);
		}
	}
	return 0;
}
